package com.lzb.permanentcalendar;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.google.gson.reflect.TypeToken;
import com.lzb.permanentcalendar.basic.utils.BroadcastReceiverUtil;
import com.lzb.permanentcalendar.bean.ScheduleBean;
import com.lzb.permanentcalendar.databinding.ActivityHomeBinding;
import com.lzb.permanentcalendar.fragment.HomeFragment;
import com.lzb.permanentcalendar.fragment.MyFragment;
import com.lzb.permanentcalendar.fragment.ScheduleFragment;
import com.lzb.permanentcalendar.fragment.ToolFragment;
import com.lzb.permanentcalendar.fragment.WeatherFragment;
import com.lzb.permanentcalendar.utils.AppSpUtils;
import com.lzb.permanentcalendar.utils.MyReceiver;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class HomeActivity extends BaseTabFragmentHomeActivity<ActivityHomeBinding> {

    private List<ScheduleBean> listRe;

    private Handler mHandler = new Handler(Looper.getMainLooper());
    private long lastCheckTime = 0;
    private Set<String> notifiedItems = new HashSet<>();
    private Runnable countdownRunnable = new Runnable() {
        @Override
        public void run() {
            if (System.currentTimeMillis() - lastCheckTime > 60000) { // 每分钟检查一次
                TimeRemind();
                lastCheckTime = System.currentTimeMillis();
            }
            if (listRe != null && listRe.size() > 0) {
                for (int i = 0; i < listRe.size(); i++) {
                    String n1 = TimeUtils.getNowString(new SimpleDateFormat("HH:mm"));
                    String t1 = TimeUtils.millis2String(listRe.get(i).getRemindTime(), new SimpleDateFormat("HH:mm"));
                    String uniqueKey = listRe.get(i).getId() + "_" + t1; // 创建唯一标识
                    if (t1.equals(n1) && !notifiedItems.contains(uniqueKey)) {
                        MyReceiver.NOTIFICATION_ID = (int) System.currentTimeMillis() % Integer.MAX_VALUE;
                        MyReceiver.showNotification(mContext, listRe.get(i).getTitle(), false);
                        notifiedItems.add(uniqueKey); // 标记为已通知
                    }
                }
            }
            // 每天午夜清空已通知记录
            if ("00:00".equals(TimeUtils.getNowString(new SimpleDateFormat("HH:mm")))) {
                notifiedItems.clear();
            }
            mHandler.postDelayed(this, 1000);
        }
    };

    @Override
    protected void initView() {
        super.initView();

        registerBroadcastReceiver();

        MyReceiver.createNotificationChannel(mContext);
        mHandler = new Handler();
    }

    @Override
    protected void initData() {
        super.initData();
        mHandler.post(countdownRunnable);
    }

    @NonNull
    @Override
    protected List<BaseTabFragmentHomeActivity<ActivityHomeBinding>.FragmentViewBinder> getFragmentViewBinders() {
        List<FragmentViewBinder> listFragment = new ArrayList<>();
        listFragment.add(new FragmentViewBinder(HomeFragment.class, R.id.llHome));
        listFragment.add(new FragmentViewBinder(ScheduleFragment.class, R.id.llSchedule));
        listFragment.add(new FragmentViewBinder(WeatherFragment.class, R.id.llWeather));
        listFragment.add(new FragmentViewBinder(ToolFragment.class, R.id.llTool));
        listFragment.add(new FragmentViewBinder(MyFragment.class, R.id.llMy));
        return listFragment;
    }

    @Override
    protected void onFragmentViewClick(View view) {
        clearSelection();
        int id = view.getId();
        if (id == R.id.llHome) {
            mDataBinding.ivHome.setImageResource(R.drawable.aarili);
            mDataBinding.tvHome.setTextColor(Color.parseColor("#AD2419"));
        } else if (id == R.id.llSchedule) {
            mDataBinding.ivSchedule.setImageResource(R.drawable.aaricheng);
            mDataBinding.tvSchedule.setTextColor(Color.parseColor("#AD2419"));
        } else if (id == R.id.llWeather) {
            mDataBinding.ivWeather.setImageResource(R.drawable.aatianqi);
            mDataBinding.tvWeather.setTextColor(Color.parseColor("#AD2419"));
        } else if (id == R.id.llTool) {
            mDataBinding.ivTool.setImageResource(R.drawable.aagongju);
            mDataBinding.tvTool.setTextColor(Color.parseColor("#AD2419"));
        } else if (id == R.id.llMy) {
            mDataBinding.ivMy.setImageResource(R.drawable.aawode);
            mDataBinding.tvMy.setTextColor(Color.parseColor("#AD2419"));
        }
    }

    @Override
    protected int getFragmentContainerId() {
        return R.id.flContainer;
    }

    @Override
    protected int onCreate() {
        return R.layout.activity_home;
    }

    private void clearSelection() {
        mDataBinding.ivHome.setImageResource(R.drawable.arili);
        mDataBinding.tvHome.setTextColor(Color.parseColor("#999999"));
        mDataBinding.ivSchedule.setImageResource(R.drawable.aricheng);
        mDataBinding.tvSchedule.setTextColor(Color.parseColor("#999999"));
        mDataBinding.ivWeather.setImageResource(R.drawable.atianqi);
        mDataBinding.tvWeather.setTextColor(Color.parseColor("#999999"));
        mDataBinding.ivTool.setImageResource(R.drawable.agongju);
        mDataBinding.tvTool.setTextColor(Color.parseColor("#999999"));
        mDataBinding.ivMy.setImageResource(R.drawable.awode);
        mDataBinding.tvMy.setTextColor(Color.parseColor("#999999"));
    }

    // 广播接收器
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            boolean f1 = intent.getBooleanExtra("message", false);
        }
    };

    public void registerBroadcastReceiver() {
        // 注册广播接收器
        IntentFilter filter = new IntentFilter();
        BroadcastReceiverUtil.registerReceiver(receiver, filter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacks(countdownRunnable);
        if (receiver != null) {
            BroadcastReceiverUtil.unregisterReceiver(receiver);
            receiver = null;
        }
    }


    public void TimeRemind() {
        List<ScheduleBean> list = getSchedule();
        listRe = new ArrayList<>();
        if (list != null && list.size() > 0) {
            listRe.addAll(list);
        }
    }

    private List<ScheduleBean> getSchedule() {
        List<ScheduleBean> listRe = new ArrayList<>();
        List<ScheduleBean> listSp = AppSpUtils.getScheduleList();
        if (listSp != null && listSp.size() > 0) {
            for (ScheduleBean bean : listSp) {
                String t = TimeUtils.millis2String(bean.getRemindTime(), new SimpleDateFormat("yyyy-MM-dd"));
                String remind = bean.getRemindType();
                String repeat = bean.getRepeatType();
                int flag = NeedRemind(t, remind, repeat);
                if (flag != -1) {
                    listRe.add(bean);
                }
            }
        }

        return listRe;
    }

    private int NeedRemind(String time, String remind, String cycle1) {
        if ("不提醒".equals(remind)) return -1;
        int cycle = getCycle(time, cycle1);
        if (cycle == -1) return -1;
        return 1;
    }

    private int getCycle(String date1, String cycle1) {
        int[] YesDay = getYesDay( date1);
        int num = 0;
        switch (cycle1) {
            case "不重复":
                num = YesDay[0];
                break;
            case "按天重复":
                num = 2;
                break;
            case "按月重复":
                num = YesDay[3];
                break;
            case "按年重复":
                int n1 = YesDay[2];
                int n2 = YesDay[3];
                num = (n1 == n2) ? 2 : -1;
                break;
            case "按周重复":
                num = YesDay[4];
                break;
        }
        return num;
    }

    private int[] getYesDay(String date1) {
        int[] num = new int[5];
        Date sDay = TimeUtils.string2Date(date1, new SimpleDateFormat("yyyy-MM-dd"));
        int aa1 = Integer.parseInt(TimeUtils.date2String(sDay, new SimpleDateFormat("yyyy")));
        int mm1 = Integer.parseInt(TimeUtils.date2String(sDay, new SimpleDateFormat("MM"))) - 1;
        int dd1 = Integer.parseInt(TimeUtils.date2String(sDay, new SimpleDateFormat("dd")));
        Calendar specifiedDate = Calendar.getInstance();
        specifiedDate.set(aa1, mm1, dd1);
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        String result = sdf1.format(specifiedDate.getTime());
        String NowDay1 = TimeUtils.getNowString(new SimpleDateFormat("yyyy-MM-dd"));
        String[] t1 = result.split("-");
        String[] n1 = NowDay1.split("-");
        String ww1 = TimeUtils.getChineseWeek(result, new SimpleDateFormat("yyyy-MM-dd"));
        String ww2 = TimeUtils.getChineseWeek(NowDay1, new SimpleDateFormat("yyyy-MM-dd"));
        int year1 = result.equals(NowDay1) ? 1 : -1;
        int y1 = t1[0].equals(n1[0]) ? 1 : -1;
        int m1 = t1[1].equals(n1[1]) ? 1 : -1;
        int d1 = t1[2].equals(n1[2]) ? 1 : -1;
        int w1 = ww1.equals(ww2) ? 1 : -1;
        num = new int[]{year1, y1, m1, d1, w1};
        return num;
    }

}